package com.zhiyou100.review.day021.homework.homework6;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/**
 * @packageName: MyReceiver
 * @className: com.zhiyou100.review.day021.homework.homework6
 * @Description: TODO 接受者
 * @author: yang
 * @date: 7/2/20
 */
public class MyReceiver {
    private static final String IP = "127.0.0.1";
    private static final int ACCEPT_PORT = 10086;
    private static final int SEND_PORT = 10000;

    public static void main(String[] args) throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket(ACCEPT_PORT);
        while (true) {

            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);

            datagramSocket.receive(datagramPacket);

            String ipAndPort = datagramPacket.getAddress().getHostAddress() + ":" + datagramPacket.getPort();
            // 对方的ip和端口

            String localhostIpAndPort = datagramSocket.getLocalAddress().getHostName() + ":" + datagramSocket.getLocalPort();
            // 本地的ip和端口

            String s = new String(bytes, 0, datagramPacket.getLength());
            System.out.println(localhostIpAndPort + "接收到 " + ipAndPort + " 的消息:: " + s);
            // 处理数据

            if (s.endsWith("END")) {
                // 如果包含END结束
                datagramSocket.close();
                break;
            }

            Scanner scanner = new Scanner(System.in);
            s = scanner.nextLine();
            datagramPacket = new DatagramPacket(s.getBytes(), 0, s.getBytes().length, InetAddress.getByName(IP), SEND_PORT);
            datagramSocket.send(datagramPacket);
            if (s.endsWith("END")) {
                break;
            }


        }
        datagramSocket.close();
    }
}
